package com.ruoyi.cms.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.cms.domain.ShortCollection;
import com.ruoyi.cms.service.IShortCollectionService;

/**
 * 短视频收藏Controller
 *
 * @author ruoyi
 * @date 2025-10-24
 */
@RestController
@RequestMapping("/short/member/collection")
public class ShortCollectionController extends BaseController
{
    @Autowired
    private IShortCollectionService shortCollectionService;

    /**
     * 获取短视频收藏状态
     */
    @GetMapping("/status")
    public AjaxResult getStatus(@RequestParam Long shortId)
    {
        try {
            Long memberId = SecurityUtils.getUserId();
            boolean isCollected = shortCollectionService.checkCollected(memberId, shortId);
            return AjaxResult.success(isCollected);
        } catch (Exception e) {
            // 未登录返回false
            return AjaxResult.success(false);
        }
    }

    /**
     * 收藏短视频
     */
    @PostMapping
    public AjaxResult collect(@RequestBody ShortCollection shortCollection)
    {
        Long memberId = SecurityUtils.getUserId();
        shortCollection.setMemberId(memberId);

        // 检查是否已收藏
        if (shortCollectionService.checkCollected(memberId, shortCollection.getShortId())) {
            return AjaxResult.error("已收藏，请勿重复操作");
        }

        int result = shortCollectionService.insertShortCollection(shortCollection);
        if (result > 0) {
            return AjaxResult.success("收藏成功");
        }
        return AjaxResult.error("收藏失败");
    }

    /**
     * 取消收藏短视频
     */
    @PostMapping("/cancel")
    public AjaxResult cancelCollection(@RequestBody ShortCollection shortCollection)
    {
        Long memberId = SecurityUtils.getUserId();
        int result = shortCollectionService.cancelCollection(memberId, shortCollection.getShortId());
        if (result > 0) {
            return AjaxResult.success("取消收藏成功");
        }
        return AjaxResult.error("取消收藏失败");
    }

    /**
     * 获取用户收藏列表
     */
    @GetMapping("/list")
    public AjaxResult list()
    {
        Long memberId = SecurityUtils.getUserId();
        ShortCollection query = new ShortCollection();
        query.setMemberId(memberId);
        return AjaxResult.success(shortCollectionService.selectShortCollectionList(query));
    }
}
